// src/hooks/useFolderPicker.ts
import {open} from '@tauri-apps/plugin-dialog';
import {useCallback} from 'react';

interface UseFolderPickerOptions {
    multiple?: boolean;
    defaultPath?: string;
    title?: string;
    directory?: boolean;
    filters?: { name: string; extensions: string[] }[];
    onSuccess?: (path: string | string[] | null) => void;
    onError?: (error: Error) => void;
}

export function useFolderPicker(options: UseFolderPickerOptions = {}) {
    const {
        multiple = false,
        defaultPath,
        title,
        directory = true, // 默认为选择文件夹
        filters,
        onSuccess,
        onError
    } = options;

    return useCallback(async () => {
        try {
            const selected = await open({
                multiple,
                defaultPath,
                title: title || '选择文件夹',
                directory,
                filters
            });

            if (onSuccess) {
                onSuccess(selected);
            }

            return selected;
        } catch (error) {
            const err = error instanceof Error ? error : new Error(String(error));
            if (onError) {
                onError(err);
            } else {
                console.error('Folder picker error:', err);
            }
            return null;
        }
    }, [multiple, defaultPath, title, directory, filters, onSuccess, onError]);
}